package com.problem.leetcode;

import com.google.common.base.Stopwatch;

import java.util.HashSet;

/**
 * 解题思路:
 * 1.获取到@前面的字符
 * 2.将句号都去掉
 * 3.从尾部开始找+ 保留开始符号到加号的位置，直到找不到为止
 *
 * @author didi
 * @DESCRIPTION
 * @create 2019-05-08 11:03
 **/

public class Problem929 {
    public int numUniqueEmails(String[] emails) {

        HashSet<String> hashSet = new HashSet<>(emails.length);


        for (String ele : emails) {
            //TODO:因为split比较耗时 而且邮件地址只有一个@ 所以使用indexOf代替split
            int    firstIndex = indexOf(ele, '@');
            String local      = ele.substring(0, firstIndex);
            String domain     = ele.substring(firstIndex, ele.length());

            int find = 0;
            find = indexOf(local, '+');
            if (find != -1) {
                local = local.substring(0, find);
            }

            local = replaceAll(local, '.');

            hashSet.add(local.concat(domain));

        }
        return hashSet.size();

    }

    /**
     * 使用这种方式要比StringBuilder性能高一些
     *
     * @param str
     * @param ch
     * @return
     */
    private String replaceAll(String str, char ch) {
        char[] chars = new char[str.length()];
        int    count = 0;
        for (int index = 0; index < str.length(); index++) {
            if (str.charAt(index) != ch) {
                chars[count++] = str.charAt(index);
            }
        }
        return String.copyValueOf(chars, 0, count);
    }

    /**
     * 因为只需要查找单个字符所以不使用String.indexOf 性能更快一些
     *
     * @param sourceStr
     * @param findStr
     * @return
     */
    private int indexOf(String sourceStr, char findStr) {

        int findIndex = -1;

        for (int index = 0; index < sourceStr.length(); index++) {
            if (sourceStr.charAt(index) == findStr) {
                return index;
            }
        }
        return findIndex;
    }

    public static void main(String[] args) {
        Stopwatch stopwatch = Stopwatch.createStarted();

        for (int index = 0; index < 1000000; index++) {
            new Problem929().numUniqueEmails(
                    new String[]{"test.email+alex@leetcode.com", "test.e.mail+bob.cathy@leetcode.com",
                                 "testemail+david@lee.tcode.com"});
        }

        stopwatch.stop();
        System.out.println(stopwatch.toString());
    }

}
